package com.tzy.makeagirlhappy.service;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * 彩虹屁
 */
public class RainBow {

    private static final String filePath = "E:\\学习\\文档\\1文本\\rainbow.txt";

    public static void main(String[] args) {
        //已废弃的URL
//        String url = "https://chp.shadiao.app/api.php?from=2271787566";
        String url = "https://api.shadiao.app/chp";
        for(int i = 0; i <= 10000; i++){
            String str = getURLContent(url);
            System.out.println(str);
            saveAsFileWriter(filePath,str);
        }
    }

    //parm：请求的url链接  返回的是json字符串
    public static String getURLContent(String urlStr) {

        //请求的url
        URL url = null;

        //建立的http链接
        HttpURLConnection httpConn = null;

        //请求的输入流
        BufferedReader in = null;

        //输入流的缓冲
        StringBuffer sb = new StringBuffer();

        try{
            url = new URL(urlStr);

            in = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8") );

            String str = null;

            //一行一行进行读入
            while((str = in.readLine()) != null) {
                sb.append( str );
            }
        } catch (Exception ex) {

        } finally{
            try{
                if(in!=null) {
                    in.close(); //关闭流
                }
            }catch(IOException ex) {

            }
        }
        String result =sb.toString();
        return result;
    }

    /**
     * 保存到文件中
     * @param filePath
     * @param content
     */
    private static void saveAsFileWriter(String filePath,String content) {

        content+="\r\n";
        FileWriter fwriter = null;
        try {
            // true表示不覆盖原来的内容，而是加到文件的后面。若要覆盖原来的内容，直接省略这个参数就好
            fwriter = new FileWriter(filePath, true);
            fwriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fwriter.flush();
                fwriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

